package yxy.cherry.gateway.internal;

import yxy.apple.logger.Logger;
import yxy.apple.logger.Logger.Level;
import yxy.apple.protobuf.Message.Parcal;
import yxy.banana.server.internal.InternalClientHandler;
import yxy.banana.socket.NetworkElement;
import yxy.banana.socket.ParcalUtility;
import yxy.cherry.gateway.Configuration;
import yxy.cherry.gateway.Reactor;
import yxy.cherry.gateway.external.GatewayServerHandler;

public class GatewayClientHandler extends InternalClientHandler {

	private static final Logger logger = Logger.create(GatewayClientHandler.class);

	@Override
	protected boolean business(Parcal parcal) throws Exception {
		NetworkElement dne = NetworkElement.assemble(parcal.getDestination());
		GatewayServerHandler external = Reactor.instance.externals().find(dne.channel());
		if (external != null) {
			// 向客户端发送信息时不提供source和destination
			if (Logger.enabled(Level.Debug)) {
				String description = ParcalUtility.toString(parcal);
//				logger.debug("转发消息到用户端...\r\n%s\r\n%s\r\n%s", this.toString(), external.toString(), description);
			}
			external.send(parcal.getTag(), 0, 0, parcal.getProto(), parcal.getData());
			// 统计流量数据到普罗米修斯，统计不可占用过多性能。
			return true;
		} else {
			String description = ParcalUtility.toString(parcal);
			logger.warn("向用户端推送消息时找不到对应的连接!\r\n%s\r\n%s", this.toString(), description);
			return false;
		}
	}

	@Override
	public int system() {
		return Configuration.shared().SystemID;
	}

	@Override
	public int cluster() {
		return Configuration.shared().ClusterID;
	}

}
